package com.gzhryc.shared_device.oem.h5.mng.controllers.device;

import com.gzhryc.common.data.dto.ListResult;
import com.gzhryc.common.logging.Logger;
import com.gzhryc.servlet.DtoConstants;
import com.gzhryc.servlet.WebUtils;
import com.gzhryc.servlet.annotation.Route;
import com.gzhryc.shared_device.iot.code.dao.db.IOTLogsRecord;
import com.gzhryc.shared_device.iot.code.dao.enums.ELogType;
import com.gzhryc.shared_device.iot.code.services.IOTLogsRecordService;
import com.gzhryc.shared_device.iot.code.services.dto.IOTLogsRecordSearch;
import com.gzhryc.shared_device.oem.h5.mng.WebConstants;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.util.Date;

public class DeviceIOTLogsController {

    static Logger log = Logger.getLogger(DeviceIOTLogsController.class);

    @Route(value = { "/device/iot_logs/list.html" })
    public String list(HttpServletRequest request) {
        request.setAttribute("typeList", ELogType.values());
        return "/device/iot_logs/list.html";
    }

    @Route(value = "/device/iot_logs/list.data")
    public ListResult<IOTLogsRecord> listData(HttpServletRequest request) {
        ListResult<IOTLogsRecord> result = new ListResult<>(DtoConstants.NULL_DATA,"暂无数据");
        try {
            IOTLogsRecordSearch search = WebUtils.getParameter(request, IOTLogsRecordSearch.class);
            Integer pageNo = WebUtils.getInteger(request, "page", 1);
            Integer pageLimit = WebUtils.getInteger(request, "limit", WebConstants.PAGE_LIMIT);
            String searchDate = WebUtils.getString(request, "searchDate");
            if (StringUtils.isNotBlank(searchDate)) {
                String[] strings = searchDate.split(" - ");
                if (strings.length == 2) {
                    Date startDate = DateUtils.parseDate(strings[0], "yyyy-MM-dd");
                    Date endDate = DateUtils.parseDate(strings[1], "yyyy-MM-dd");
                    search.setStartDate(startDate);
                    search.setEndDate(endDate);
                }
            }

            result.getBody().setTotal(IOTLogsRecordService.self().countBySearch(search));
            result.getBody().setData(IOTLogsRecordService.self().findBySearch(search, pageNo, pageLimit));

            if (result.getBody().getData() != null && result.getBody().getData().size() > 0) {
                result.setCode(DtoConstants.SUCCESS,null);
            }
        }catch (ParseException e){
            log.error(e.getMessage(),e);
            result.setMsg("查询时间解析失败");
        }
        return result;
    }
}
